package com.eagle.epay.controller;

import com.eagle.epay.common.ResultVO;
import com.eagle.epay.constant.EPayConstant;
import com.eagle.epay.constant.ResponseEnum;
import com.eagle.epay.entity.User;
import com.eagle.epay.exception.ServiceException;
import com.eagle.epay.service.IUserService;
import com.eagle.epay.util.ResultVOUtil;
import com.eagle.epay.vo.LoginVO;
import com.eagle.epay.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RestController
@Slf4j
public class UserController {
	@Autowired
	private IUserService userService;

	@PostMapping("/user/register")
	public ResultVO register(@Valid @RequestBody UserVO userVO){
		log.info("the user info, {}", userVO.toString());
		User user = new User();
		BeanUtils.copyProperties(userVO,user);
		this.userService.registerUser(user);
		return ResultVOUtil.success();
	}

	@PostMapping("/user/login")
	public ResultVO<User> login(@Valid @RequestBody LoginVO loginVO,
								HttpSession session){
		User login = userService.login(loginVO.getUsername(), loginVO.getPassword());
		session.setAttribute(EPayConstant.CURUSER,login);
		return ResultVOUtil.success(login);
	}

	@GetMapping("/user")
	public ResultVO<User> userInfo(HttpSession session){
		User user = (User) session.getAttribute(EPayConstant.CURUSER);
		return ResultVOUtil.success(user);
	}

	/**
	 * {@link TomcatServletWebServerFactory} #getSessionTimeoutInMinutes
	 *
	 */
	@PostMapping("/user/logout")
	public ResultVO<User> logout(HttpSession session){
		log.info("user/logout sessionid={}", session.getId());
		User user = (User) session.getAttribute(EPayConstant.CURUSER);
		session.removeAttribute(EPayConstant.CURUSER);
		return ResultVOUtil.success();
	}
}
